from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from rest_framework import exceptions
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.django.auth import jwt_login, jwt_logout
from .. import serializers


class Login(GenericAPIView):
    serializer_class = serializers.LoginSerializer
    permission_classes = []

    # @csrf_exempt
    def post(self, request, format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        access_token = serializer.validated_data['access_token']
        refresh_token = serializer.validated_data['refresh_token']
        token_info = {
            settings.TOKEN_ACCESS_CLAIM: access_token,
            settings.TOKEN_REFRESH_CLAIM: refresh_token,
        }
        jwt_login(request, user)
        return Response({
            'message': '登录成功',
            'data': token_info
        })


class Logout(GenericAPIView):
    serializer_class = serializers.LogoutSerializer
    permission_classes = []

    def post(self, request):
        if isinstance(request.user, AnonymousUser):
            raise exceptions.NotAuthenticated
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        refresh_token = serializer.validated_data['refresh_token']
        jwt_logout(request, refresh_token)
        return Response({'message': '成功退出'})
